/*
 * @Author: liusheng
 * @Date: 2022-06-26 15:19:37
 * @LastEditors: liusheng
 * @LastEditTime: 2022-06-26 15:49:26
 * @Description: 剑指 Offer II 082. 含有重复元素集合的组合
 * email:liusheng613@126.com
 * Copyright (c) 2022 by liusheng/liusheng, All Rights Reserved. 
 * 
 剑指 Offer II 082. 含有重复元素集合的组合
给定一个可能有重复数字的整数数组 candidates 和一个目标数 target ，找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次，解集不能包含重复的组合。 

 

示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]
 

提示:

1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
 

注意：本题与主站 40 题相同： https://leetcode-cn.com/problems/combination-sum-ii/
 */

#include "header.h"

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<int> prefix;
        vector<vector<int>> result;
        sort(candidates.begin(),candidates.end());
        combinationSum2(candidates,target,0,prefix,result);
        return result;
    }
private:
    void combinationSum2(vector<int>& candidates, int target,int curIndex,vector<int> &prefix,vector<vector<int>> & result)
    {
        if (target == 0)
        {
            result.push_back(prefix);
            return;
        }
        
        if (curIndex == candidates.size())
        {
            return;
        }
        
        if (target < 0)
        {
            return;
        }
        
        // while (curIndex > 0 && curIndex < candidates.size() && candidates[curIndex] == candidates[curIndex-1])
        // {
        //     ++curIndex;
        // }
        // prefix.push_back(candidates[curIndex]);
        // combinationSum2(candidates,target - candidates[curIndex],curIndex + 1,prefix,result);
        // prefix.pop_back();
        // combinationSum2(candidates,target,curIndex + 1,prefix,result);
        for (int i = curIndex; i < candidates.size(); ++i)
        {
            if (i > curIndex && candidates[i] == candidates[i-1])
            {
                continue;
            }
            prefix.push_back(candidates[i]);
            combinationSum2(candidates,target - candidates[i],i + 1,prefix,result);
            prefix.pop_back();
        }
    }
};
